import { post } from './Request';

export async function add(domain, param = {}) {
    const { data } = await post(`api/${domain}/add`, param);
    return data || false;
}

export async function update(domain, mu, param = {}) {
    const { data } = await post(`api/${domain}/update`, {
        mu,
        data: param,
    });
    return data || false;
}

export async function one(domain, mu) {
    const { data } = await post(`api/${domain}/one`, { mu });
    return data || {};
}

export async function list(domain, param = {}) {
    const { data } = await post(`api/${domain}/list`, param);
    return data || [];
}

export async function page(domain, param = {}, pageNum = 1, pageSize = 15) {
    let { page, pages, mark } = await post(`api/${domain}/page`, {
        pageNum,
        pageSize,
        data: param,
    });
    if (page) {
        let { list = [], total = 0, current = 1 } = page;
        return { list, total, current, mark };
    }
    if (pages) {
        pages.forEach((item) => {
            if (!item.list) {
                item = { list: [], total: 0, current: 1 };
            }
        });
        return { pages, mark };
    }
}

export async function search(uri, param = {}, pageNum = 1, pageSize = 15) {
    const { page, mark } = await post(uri, { pageNum, pageSize, data: param });
    let { list = [], total = 0, current = 1 } = page;
    return { list, total, current, mark };
}
export async function query(uri, param = {}) {
    const { data } = await post(uri, param);
    return data || {};
}

export async function submit(uri, param = {}) {
    const { data } = await post(uri, param);
    return data || {};
}

export function throttle(fn, data = {}, delay = 500, context = null) {
    clearTimeout(fn.timeoutId);
    fn.timeoutId = setTimeout(function () {
        fn.call(context, data);
    }, delay);
}
